package com.nursinghome.admin.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.nursinghome.admin.mapper.UserMapper;
import com.nursinghome.admin.service.UserService;
import com.nursinghome.bean.User;
import com.nursinghome.exception.NurisingHomeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User selectByUsername(String username) {

        return null;
    }

    @Override
    public User login(String username, String password) throws NurisingHomeException {
        String md5Pwd = SecureUtil.md5(SecureUtil.md5(password));
        User user = userMapper.selectByUsername(username);
        if (user == null){
            throw new NurisingHomeException("用户名不正确");
        }

        if (!md5Pwd.equals(user.getPassword())){
            throw new NurisingHomeException("密码不正确,请重新输入");
        }
            return user;
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public Boolean updateByUse(String username, String password, String newPassword, String confirmPassword) throws NurisingHomeException {
        // 判断密码是否正确
        User byUsername = userMapper.selectByUsername(username);
        String pwdMd5 = SecureUtil.md5(SecureUtil.md5(password));

        if (byUsername == null){
            throw new NurisingHomeException("用户名不正确");
        }
        if (!pwdMd5.equals(byUsername.getPassword())) {
            throw new NurisingHomeException("密码不正确,请重新输入");
        }
        // 判断两次密码是否一致
        if (!newPassword.equals(confirmPassword)){
            throw new NurisingHomeException("两次密码不一致");
        }
        User user = new User(null, username, newPassword, null);
        return userMapper.updateByUse(user) > 0;
    }
}
